 /*@author hxd
  * 我在公司内部“东西”上查到一个，但不能确定是不是符合标准，你参考吧！配电盘上的模拟线应按电压等级涂不同颜色。
  * 电压由高至低应按淡黄、紫、朱红、鲜黄、绛红、深兰等顺序（500KV、220KV、110KV、35KV、10KV、6KV）。
  */
 var nomalColor = "#ff0000";
 var hoverColor = "#0000ff";
 var selectColor = "#00ff00";

 function hover_in() {
   //var oldwidth=this.attr("stroke-width");
   //this.attr({"stroke-width":oldwidth+2});
   this.attr({
     "stroke": hoverColor
   });
 }

 function hover_out() {
   this.attr({
     "stroke": nomalColor
   });
 }

 function click_select() {
   this.attr({
     "stroke": selectColor
   });
   // var resize = this.paper.el("rect").attr(this.getBBox());
   // resize.drag(resizeing,begin_resize,end_resize);

 }


 function dbclick_edit() {
   alert("");
 }
 //初始化matrix
 function drag_start(x, y, target) {

   this.newtrans = this.transform().localMatrix;
 };
 //设置只有x移动的matrix
 function drag_move(dx, dy, x, y, target) {

   this.trans = new Snap.Matrix();
   this.trans.translate(dx, 0);
   var node = this.node;
   //通过遍历父类，找到最上层的 g块元素，作为移动的对象
   while (node.parentNode.nodeName == "g") {
     node = node.parentNode;
   }
   this.node = node;

   this.trans.add(this.newtrans);

   this.transform(this.trans);
 };

 function drag_stop(target) {
   //alert(target);

 }
 //母线分段 母线的条数  短路器的宽度   BreakerWidth


 //====================母线
 Snap.plugin(function(Snap, Element, Paper, global) {
   var proto = Paper.prototype,
     is = Snap.is,
     clone = Snap._.clone,
     has = "hasOwnProperty",
     p2s = /,?([a-z]),?/gi,
     toFloat = parseFloat,
     math = Math,
     PI = math.PI,
     mmin = math.min,
     mmax = math.max,
     pow = math.pow,
     abs = math.abs,
     elproto = Element.prototype;

   Snap.busLine = function() {
     alert("Snap");
   };
   Element.prototype.busLine = function() {
     alert("Element");
   };

   // 通过ajax 获取需要显示一次图的数据 Electric wiring diagram
   proto.EWDiagram = function(url) {
     var paper = this;
     $.ajax({
       type: "post",
       url: url,
       // data: data,
       dataType: "json",
       complete: function() {
         console.dir("加载完成");
       },
       success: function(data) {
         parseData(data);
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         console.log(textStatus);
       }

     });
     //采用先 缓存绘制，缓存完了之后再一次性绘制。
     //设计到修改的就是 x的坐标，因为设备的数量是变化的，设备的位置可能不是死的。
     function parseData(data) {
       var trsform_width = {
         1: 200,
         2: 200

       };
       var eqpt_width = {
         1: 400,
         2: 200,
         3: 200,
         4: 120,
         5: 300,
         6: 100,
         9: 60
       };
       try {

         // var a=200,b=300,c=0;
         //   c=Math.max(a,b);
         //  alert(c);
         if (data.bus) {
           var buss = data.bus;
           var bus_width = 0;
           $.each(buss, function(index, bus) {

             if (bus.children) {

               var trfs = bus.children;
               var trf_width = 0;
               $.each(trfs, function(index, trf) {
                 var noTopBus = trf.children;
                 var yx = trf.measure.yx;
                 if (yx.length == 2) {
                   if (noTopBus.length < 2) {
                     var nbus_width = 0;

                     $.each(noTopBus, function(index, nbus) {

                       var setWires = nbus.children;
                       var set_width = 0; //计算最底层的设备需要的宽度
                       $.each(setWires, function(index, setwire) {
                         setwire.minWidth = eqpt_width[setwire.type];
                         set_width += eqpt_width[setwire.type]

                       });
                       //非顶层母线的宽度为，所有设备的宽度和 与 非顶层母线的默认宽度中 最大的那个
                       nbus.minWidth = Math.max(eqpt_width[nbus.type], set_width);

                       nbus_width += nbus.minWidth;


                     });

                     //变压器 所占用的宽度，为下面母线所占用的宽度与 变压器本身的宽度中最大的
                     trf.minWidth = Math.max(trsform_width[1], nbus_width);

                     trf.leftWidth = noTopBus[0].minWidth / 2; //双卷变压器 距离左边的距离为 下面低压母线长度的一半

                     trf_width += trf.minWidth;
                   } else {
                     throw new Error("两卷变压器配置了2条低压母线！" + JSON.stringify(noTopBus));
                   }



                 } else if (yx.length == 3) {
                   if (noTopBus.length < 3) {
                     var nbus_width = 0;
                     trf_width += 50; //两条低压母线 之间的间隔
                     $.each(noTopBus, function(index, nbus) {

                       var setWires = nbus.children;
                       var set_width = 0; //计算最底层的设备需要的宽度
                       $.each(setWires, function(index, setwire) {
                         setwire.minWidth = eqpt_width[setwire.type];
                         set_width += eqpt_width[setwire.type]
                       });
                       //非顶层母线的宽度为，所有设备的宽度和 与 非顶层母线的默认宽度中 最大的那个
                       nbus.minWidth = Math.max(eqpt_width[nbus.type], set_width);

                       nbus_width += nbus.minWidth;

                     });

                     //变压器 所占用的宽度，为下面母线所占用的宽度与 变压器本身的宽度中最大的

                     trf.minWidth = Math.max(trsform_width[1], nbus_width);
                     trf.leftWidth = noTopBus[0].minWidth + 25; //三卷变压器的 距离左边的距离为 左边母线的长度+基本母线间距的一半
                     trf_width += trf.minWidth;


                   } else {
                     throw new Error("三卷变压器配置了3条低压母线！" + JSON.stringify(noTopBus));
                   }


                 } else {
                   throw new Error("解析变压器数据出错！" + JSON.stringify(trf));
                 }


               });

             }
             bus.minWidth = Math.max(eqpt_width[bus.type], trf_width);

             bus_width += bus.minWidth;
           });

         }


         if (data.bus) {


           var buss = data.bus,
             busCount = buss.length,
             pinLen = Snap.avc.pinLen,
             breakerLen = pinLen * 3,
             //两边留出 一个管脚的距离， 还要留出断路器的距离
             busLen = Snap.avc.width / busCount - pinLen * 2 - (busCount - 1) * breakerLen
           var Xaxis = 0;
           $.each(data.bus, function(index, bus) {


             if (index > 0) {
               var field = buss[index - 1].id + "-" + buss[index].id; //1000-1001
               // 母线连接 断路器
               paper.busBreaker(Xaxis, pinLen * 3, data.breaker[field]);
               Xaxis += breakerLen;

               paper.busLine(Xaxis, pinLen * 3, bus);
             } else {

               paper.busLine(0, pinLen * 3, bus);
               Xaxis += bus.minWidth;

             }
           });


         } else {
           console.error("数据结构不合法！");
         }
       } catch (e) {
         alert(e.name + ": " + e.message);
       }
     }



   }


   proto.busLine = function(x, y, data) {


     var path = ["M", x, y, "l", data.minWidth, 0, "z"].join(" ");
     var p = this.path(path).attr(Snap.avc.pathattr);

     var bb = p.getBBox();
     //母线的名称
     var text = this.text(x + bb.width / 2, y - bb.height / 2 - Snap.avc.strokeWidth / 2 - Snap.avc.textmargin, data.name).attr(Snap.avc.textattr);



     var g = this.g();

     //解析 母线量测 
     var paper = this;
     if (data.measure) {
       var measure = data.measure;
       if (measure.yc) {
         var yc = measure.yc; //母线需要显示的遥测

         var len = yc.length; //遥测的个数
         var margin = 20;
         $.each(yc, function(index, item) {
           //量测的名称
           var text = paper.text(x, y - (len - index) * margin - Snap.avc.strokeWidth / 2 - Snap.avc.textmargin, item.name).attr(Snap.avc.textattr);

           //量测的值
           text = paper.text(x + 60, y - (len - index) * margin - Snap.avc.strokeWidth / 2 - Snap.avc.textmargin, 'xxx.xx').attr(Snap.avc.textattr).attr("id", item.id);;

         });
       }
     }
     //解析 变压器
     if (data.children) {
       var trformer = data.children; //变压器的数据
       var len = trformer.length; //变压器的个数
       var minLen = len * 200; //每个变压器知识占用200的空间
       length = length < minLen ? minLen : length;
       var Xaxis = 0;
       $.each(trformer, function(index, trf) {
         //根据变压器的个数均匀分配显示空间,  

         paper.transformer_withBreaker(x + trf.leftWidth, y, trf, length);

       });
     }


     p.hover(hover_in, hover_out);
     return p; //返回母线，不包括文字，在组合的时候会用到母线的边框
   };

   proto.transformer = function(x, y, data) {
     //a rx ry xr large sweep x y
     // rx ry 半径
     // xr  X轴水平方向的夹角
     // large  大小弧
     // sweep  圆心在起点的顺时针反向 还是逆时针方向  1 顺时针
     // x y  终点 
     p = this.path().attr(Snap.avc.pathattr);
     p.attr({
       path: ["M", x, y, "l 0 20 a15 15 0 1 0 15 15 15 15 1 0 0 -15 -15 m 0 50 a15 15 0 1 1 15 -15  15 15 0 0 1  -15 15   l 0 20 z"].join(" ")
     });

     p.click(click_select);
     p.dblclick(dbclick_edit);
     p.hover(hover_in, hover_out);
     var bb = p.getBBox();
     var y2 = y + bb.height;
     var x = x - 80;
     var margin = 20;

     text = this.text(x, y - 10, data[0].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y - 10, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[0].id);

     text = this.text(x, y + 10, data[1].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y + 10, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[1].id);

     text = this.text(x, y + 30, data[2].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y + 30, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[2].id);


     text = this.text(x, y2 - 10, data[3].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y2 - 10, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[3].id);

     text = this.text(x, y2 + 10, data[4].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y2 + 10, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[4].id);

     text = this.text(x, y2 + 30, data[5].name).attr(Snap.avc.textattr);
     text = this.text(x + margin, y2 + 30, "xxx.xx").attr(Snap.avc.textattr).attr("id", data[5].id);

     var g = this.g();
     g.add(p, text);
     return g;
   };

   proto.three_transformer = function(x, y, data, yx) {

     var paper = this,
       p = this.path().attr(Snap.avc.pathattr);

     p.attr({
       path: ["M", x, y, "l 0 20 a15 15 0 1 0 15 15 15 15 1 0 0 -15 -15   m -10 10 a15 15 0 1 0 15 15 15 15 1 0 0 -15 -15  m 20 0 a15 15 0 1 0 15 15 15 15 1 0 0 -15 -15  m 15 20 l 50 20 m 0 0 l0 20  m -100 -40 l -50 20 m0 0 l 0 20 "].join(" ")
     });
     p.click(click_select);
     p.dblclick(dbclick_edit);
     p.hover(hover_in, hover_out);
     var bb = p.getBBox();
     var x = x - 140;
     var margin = 20;
     // 判断变压器 量测 的数量，必须是 偶数
     var data_len = data.length - 1;
     var yx_len = yx.length;
     if (data_len % yx_len == 1) {
       throw new Error("变压器类型错误，或是量测配置错误！\n\n" + JSON.stringify(noTopBus));

     } else {

       $.each(yx, function(index) {

         if (index == 1) {
            x = x - bb.width / 2;
             y = y + bb.height;
         } else if (index == 2) {
            x = x + bb.width ;
         }
         for (var i = 0; i < 3; i++) {

           var item = data[index * 3 + i];
           if (item) {
             text = paper.text(x, y + i * 20, item.name).attr(Snap.avc.textattr);
               text = paper.text(x + margin, y+ i * 20  , "xxx.xx").attr(Snap.avc.textattr).attr("id", item.id);
           }
         }


       });
     }

     // text = this.text(x + bb.width / 2 + Snap.avc.strokeWidth / 2, y + bb.height / 2, values).attr(Snap.avc.textattr);
     // text = this.text(x, y - 10, data[0].name).attr(Snap.avc.textattr);
     // text = this.text(x + margin, y - 10, "xxx.xx").attr(Snap.avc.textattr);

     // text = this.text(x, y + 10, data[1].name).attr(Snap.avc.textattr);
     // text = this.text(x + margin, y + 10, "xxx.xx").attr(Snap.avc.textattr);


     // text = this.text(x, y + 30, data[2].name).attr(Snap.avc.textattr);
     // text = this.text(x + margin, y + 30, "xxx.xx").attr(Snap.avc.textattr);


     // var x2 = x - bb.width / 2;
     // var y2 = y + bb.height;

     // text = this.text(x2, y2 - 10, data[3].name).attr(Snap.avc.textattr);
     // text = this.text(x2 + margin, y2 - 10, "xxx.xx").attr(Snap.avc.textattr);

     // text = this.text(x2, y2 + 10, data[4].name).attr(Snap.avc.textattr);
     // text = this.text(x2 + margin, y2 + 10, "xxx.xx").attr(Snap.avc.textattr);

     // text = this.text(x2, y2 + 30, data[5].name).attr(Snap.avc.textattr);
     // text = this.text(x2 + margin, y2 + 30, "xxx.xx").attr(Snap.avc.textattr);

     // var x3 = x + bb.width / 2;
     // text = this.text(x3, y2 - 10, data[6].name).attr(Snap.avc.textattr);
     // text = this.text(x3 + margin, y2 - 10, "xxx.xx").attr(Snap.avc.textattr);

     // text = this.text(x3, y2 + 10, data[7].name).attr(Snap.avc.textattr);
     // text = this.text(x3 + margin, y2 + 10, "xxx.xx").attr(Snap.avc.textattr);

     // text = this.text(x3, y2 + 30, data[8].name).attr(Snap.avc.textattr);
     // text = this.text(x3 + margin, y2 + 30, "xxx.xx").attr(Snap.avc.textattr);

     var g = this.g();
     g.add(p, text);
     return g;
   };
   proto.busBreaker = function(x, y, data) {
     var path = "l 0 20  m 0 0 20 0 0 -5 20 0 0 5 m -20 0 l 0 5 20 0 0 -5 20 0 m 0 0  0 -20";
     if (data) {
       //没有断路器 添加的显示状态
       if (data.type == "D9") {
         path = "m 10 0 l 0 10 40 0 0 -20 -40 0 0 10";
         //有断路器，直接显示
       } else {
         path = "l 0 20  m 0 0 20 0 0 -5 20 0 0 5 m -20 0 l 0 5 20 0 0 -5 20 0 m 0 0  0 -20";
       }
     }
     var p = this.path().attr({
       stroke: nomalColor,
       "stroke-width": 1,
       id: "breaker",
       x: 0,
       y: 0,
       fill: "#f00"
     });
     //解决fireffox 移动 到线段中间进行绘制的时候出现，由于线条宽度导致移动位置偏差线宽的bug
     //最好 m的时候不要移动到线段的中间位置，不然会出现由于线条宽度照成的误差
     p.attr({
       path: ["M", x, y, path].join(" ")
     }).attr("id", "ffff");

     p.click(click_select);
     p.dblclick(dbclick_edit);
     p.hover(hover_in, hover_out);
     //在开关旁边显示 开关名称
     var bb = p.getBBox();
     var text = this.text(x, y + bb.height * 2, data.name).attr(Snap.avc.textattr);

     var g = this.g();
     g.add(p, text);
     g.click(function() {
       alert(data.id);
     }).hover(hover_in, hover_out);
     return g;

   };
   //proto.three_transformer={};
   // proto.three_transformer.getBox=function(){
   //   alert("OK");
   //    return this.getBBox();
   // };
   proto.breaker = function(x, y, data) {

     var p = this.path().attr({
       stroke: nomalColor,
       "stroke-width": 5,
       id: "breaker",
       title: "asdf",
       x: 0,
       y: 0
     });
     //解决fireffox 移动 到线段中间进行绘制的时候出现，由于线条宽度导致移动位置偏差线宽的bug
     //最好 m的时候不要移动到线段的中间位置，不然会出现由于线条宽度照成的误差
     p.attr({
       path: ["M", x, y, "l 0 20 ,5 0 ,0 30, -5 0 m 0 -30 l -5 0 0 30 5 0 0 20"].join(" ")
     }).attr("id", data.id);

     p.click(click_select);
     p.dblclick(dbclick_edit);
     p.hover(hover_in, hover_out);
     //在开关旁边显示 开关名称
     var bb = p.getBBox();
     var text = this.text(bb.width / 2 + Snap.avc.strokeWidth + 5 + x, y + bb.height / 2, data.name).attr(Snap.avc.textattr);
     var g = this.g();
     g.add(p, text);
     //  g.drag(drag_move, drag_start, drag_stop);
     return g;
   };
   proto.transformer_withBreaker = function(x, y, data, busLength) {
     //根据遥信的数量判断是三圈变 还是普通变压器
     var measure = data.measure;
     var yx = measure.yx;
     var yc = measure.yc;
     var yxCount = yx.length;
     var paper = this;
     var g = this.g();
     //解析低压母线
     var noTopBus = data.children;

     //三卷变 
     if (yxCount == 3) {

       //高压测开关
       var breaker1 = paper.breaker(x, y, yx[0]);
       var bb1 = breaker1[0].getBBox();
       var x1 = x,
         y1 = y + bb1.height;
       var transf = this.three_transformer(x1, y1, yc, yx);
       var bb2 = transf[0].getBBox();
       //中压侧
       var x2 = x1 - bb2.width / 2,
         y2 = y1 + bb2.height;
       var breaker2 = this.breaker(x2, y2, yx[1]);

       var bb3 = breaker2[0].getBBox();
       y2 = y2 + bb3.height;



       //低压侧
       var x3 = x1 + bb2.width / 2,
         y3 = y1 + bb2.height;
       var breaker3 = this.breaker(x3, y3, yx[2]);

       var noTopBus_len = noTopBus.length
         // 双卷变压器只能配置一条低压母线
       if (noTopBus_len < 2) {
         throw new Error("三卷变压器配置了只条低压母线！\n\n" + JSON.stringify(noTopBus));
       } else if (noTopBus_len == 2) {
         paper.noTopBus(x2 - noTopBus[0].minWidth + 50, y2, noTopBus[0]);

         paper.noTopBus(x3 - 50, y2, noTopBus[1]);
       } else {
         throw new Error("三卷变压器配置多条母线！\n\n" + JSON.stringify(noTopBus));
       }


       //普通两卷变
     } else if (yxCount == 2) {
       //高压测 开关
       var breaker1 = this.breaker(x, y, yx[0]);

       var bb1 = breaker1[0].getBBox();
       var x1 = x,
         y1 = y + bb1.height;
       var transf = this.transformer(x1, y1, yc, yx);

       var bb2 = transf[0].getBBox();
       //低压侧 开关
       var x2 = x1,
         y2 = y1 + bb2.height;
       var breaker2 = this.breaker(x2, y2, yx[1]);
       var bb3 = breaker2[0].getBBox();
       y2 = y2 + bb3.height;


       var noTopBus_len = noTopBus.length
         // 双卷变压器只能配置一条低压母线
       if (noTopBus_len > 1) {
         throw new Error("双卷变压器配置了两条低压母线！\n\n" + JSON.stringify(noTopBus));
       } else if (noTopBus_len == 1) {
         //默认低压母线的长度 为



         paper.noTopBus(x2 - noTopBus[0].minWidth / 2, y2, noTopBus[0]);



       }
     } else {
       throw new Error("解析变压器数据出错！" + JSON.stringify(data));
     }



     return g;
   };
   proto.noTopBus = function(x, y, data) {

     //x = x - data.minWidth / 2;
     var paper = this,
       path = ["M", x, y, "l", data.minWidth, 0, "z"].join(" ");
     var p = this.path(path).attr(Snap.avc.pathattr);

     var bb = p.getBBox();
     //母线的名称

     var text = this.text(x + bb.width / 2, y - bb.height / 2 - Snap.avc.strokeWidth / 2 - Snap.avc.textmargin, data.name).attr(Snap.avc.textattr);
     var setWire = data.children;

     var setWireCount = setWire.length;
     var margin = 100;
     var Xaxis = 0;
     $.each(setWire, function(index, item) {
       if (Xaxis == 0) //第一个低压母线设备距离左边的距离
       {
         Xaxis = item.minWidth * 2 / 3;
       }
       paper.setWire_withBreaker(x + Xaxis, y, item);
       Xaxis += item.minWidth;
     });

     return p;
   };
   proto.setWire_withBreaker = function(x, y, data) {

     var measure = data.measure;
     var yc = measure.yc,
       yx = measure.yx;
     //高压测 开关
     var breaker1 = this.breaker(x, y, yx[0]);

     var bb1 = breaker1[0].getBBox();
     var x1 = x,
       y1 = y + bb1.height;
     var transf = this.setWire(x1, y1, yc);
   };

   proto.setWire = function(x, y, data) {
     var paper = this,
       p = this.path().attr({
         stroke: nomalColor,
         "stroke-width": 3,
         id: "breaker",
         fill: "#fff",
         x: 0,
         y: 0
       });
     //解决fireffox 移动 到线段中间进行绘制的时候出现，由于线条宽度导致移动位置偏差线宽的bug
     //最好 m的时候不要移动到线段的中间位置，不然会出现由于线条宽度照成的误差
     p.attr({
       path: ["M", x, y, "l 0 20 a10 10 0 1 0 10 10  a10 10 1 0 0 -10 -10 m 0 15 a10 10 0 1 0 10 10  a10 10 1 0 0 -10 -10 m 0 20 l 0 20 a10 10 0 1 0 10 10  a10 10 1 0 0 -10 -10 m -8 10 c 0 0 5 -8 8 0 ,0 0 5 8 8 0"].join(" ")
     }).attr("id", data.id);

     p.click(click_select);
     p.dblclick(dbclick_edit);
     p.hover(hover_in, hover_out);
     //在开关旁边显示 开关名称
     var bb = p.getBBox();

     var g = this.g();
     var lineMargin = 20;
     var nameValueSpace = 20;
     x = x - 100;
     $.each(data, function(index, item) {

       var text = paper.text(bb.width / 2 + Snap.avc.strokeWidth + 5 + x, y + (index + 1) * lineMargin, item.name).attr(Snap.avc.textattr);

       g.add(p, text);
       paper.text(bb.width / 2 + Snap.avc.strokeWidth + x + nameValueSpace, y + (index + 1) * lineMargin, "xxx.xxx").attr(Snap.avc.textattr);

       g.add(p, text);
     });



     //  g.drag(drag_move, drag_start, drag_stop);
     return g;
   };

 });

 // 公共属性
 Snap.avc = {
   pinLen: 20, //基本的管脚的长度
   width: 1000,
   height: 1000,
   textattr: {
     font: '14px Arial, sans-serif',
     fill: '#000',
     "text-anchor": "start",
     href: "tttt"
   },
   strokeWidth: 5,
   textmargin: 10,
   nomalColor: "#ff0000",
   hoverColor: "#0000ff",
   selectColor: "#00ff00",
   pathattr: {
     stroke: "#ff0000",
     strokeWidth: 5,
     fill: '#fff',
   },
   measureType: {
     "yx": 0,
     "yc": 1,
     "yk": 2,
     "yt": 3
   },
   eqptEnum: {
     "System": 0,
     "TopBus": 1,
     "TransFormer": 2,
     "NoTopBus": 3,
     "SetWire": 4,
     "Svg": 5,
     "Cap": 6,
     "Fans": 7,
     "PVI": 8,
     "Bresker": 9,
     "Cluster": 10
   }
 };
 /*
 //自定义属性，通过title来获取指定的item,href,在点击的时候会跳转到对应界面。
 Raphael.fn.getItemByTitle=function(title){

 var bot = this.bottom;
 while (bot) {
 if (bot.attr("title") == title) {
 return bot;
 }
 //alert(bot.id);
 //bot.attr({fill:"#00ff00"});
 bot = bot.next;
 }
 return null;
 };
 */